@file:OptIn(ExperimentalMaterial3Api::class)

package com.fishingwithme.android.ui.screens.spots

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MyLocation
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.ImageUploader
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.SpotsViewModel
import com.fishingwithme.android.utils.EventBus
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddSpotScreen(
    navController: NavController,
    viewModel: SpotsViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val coroutineScope = rememberCoroutineScope()

    // 监听地图数据事件
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            try {
                EventBus.mapDataEvent.collect { event ->
                    val mapData = event.data

                    if (mapData.containsKey("navigationPoints")) {
                        val navPoints = mapData["navigationPoints"] as? List<*>
                        if (navPoints != null) {
                            val positions = navPoints.mapNotNull { point ->
                                if (point is Map<*, *>) {
                                    val lat = point["latitude"] as? Double ?: 0.0
                                    val lng = point["longitude"] as? Double ?: 0.0
                                    Position(lat, lng)
                                } else {
                                    null
                                }
                            }
                            if (positions.isNotEmpty()) {
                                viewModel.updateLocation(
                                    positions[0].latitude,
                                    positions[0].longitude
                                )
                                viewModel.updatePoints(positions)
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("AddSpotScreen", "${e.message}")
            }
        }
    }

    // 加载属性
    LaunchedEffect(Unit) {
        if (uiState.props.fishTypes.isEmpty() && !uiState.isLoading) {
            viewModel.loadProps()
        }
    }

    // 监听保存成功状态
    LaunchedEffect(uiState.isSaveSuccess) {
        if (uiState.isSaveSuccess && !uiState.isLoading) {
            navController.popBackStack()
            viewModel.resetSaveState()
        }
    }

    suspend fun onPictureUpload(file: File): Flow<Result<String>> {
        return viewModel.uploadFile(file)
    }

    // 优化的UI组件 - 提高性能版本
    @Composable
    fun RadioButtonWithLabel(label: String, selected: Boolean, onSelect: () -> Unit) {
        // 直接使用颜色配置，MaterialTheme会自动管理
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(AppDimensions.SPACING_8)
                .clickable(enabled = !uiState.isLoading) { if (!uiState.isLoading) onSelect() }
        ) {
            RadioButton(
                selected = selected,
                onClick = { if (!uiState.isLoading) onSelect() },
                colors = RadioButtonDefaults.colors(
                    selectedColor = MaterialTheme.colorScheme.primary,
                    unselectedColor = MaterialTheme.colorScheme.onSurfaceVariant
                ),
                enabled = !uiState.isLoading
            )
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
            Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }

    @Composable
    fun CheckboxWithLabel(label: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
        // 直接使用颜色配置，MaterialTheme会自动管理
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(AppDimensions.SPACING_8)
                .clickable(enabled = !uiState.isLoading) { if (!uiState.isLoading) onCheckedChange(!checked) }
        ) {
            Checkbox(
                checked = checked,
                onCheckedChange = { if (!uiState.isLoading) onCheckedChange(it) },
                colors = CheckboxDefaults.colors(
                    checkedColor = MaterialTheme.colorScheme.primary,
                    uncheckedColor = MaterialTheme.colorScheme.onSurfaceVariant,
                    checkmarkColor = MaterialTheme.colorScheme.onPrimary
                ),
                enabled = !uiState.isLoading
            )
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
            Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }

    // PropertySection组件，将title参数设为可选项
    @Composable
    fun PropertySection(title: String = "", content: @Composable () -> Unit) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_12),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            ),
            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
        ) {
            Column(modifier = Modifier.padding(AppDimensions.SPACING_4)) {
                if (title.isNotEmpty()) {
                    Text(
                        text = title,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(bottom = AppDimensions.SPACING_12)
                    )
                }
                content()
            }
        }
    }

    // 优化的3列网格布局 - 提高性能版本
    @Composable
    fun ThreeColumnGrid(items: List<@Composable () -> Unit>) {
        // 直接渲染，减少额外的组合层次
        Column {
            // 计算需要多少行
            val rowCount = (items.size + 2) / 3

            // 逐行渲染
            for (i in 0 until rowCount) {
                // 计算当前行的起始索引
                val startIndex = i * 3

                Row(modifier = Modifier.fillMaxWidth()) {
                    // 位置1
                    if (startIndex < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    // 位置2
                    if (startIndex + 1 < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex + 1]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    // 位置3
                    if (startIndex + 2 < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex + 2]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }
                }
            }
        }
    }

    Scaffold(
        containerColor = MaterialTheme.colorScheme.background
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize()) {
            // 表单内容 - 使用LazyColumn替代Column+verticalScroll以提高性能
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(AppDimensions.SPACING_16),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_16),
                content = {
                    // 照片上传
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_8)) {
                                PropertySection() {
                                    ImageUploader(
                                        pictures = uiState.photos,
                                        maxImages = 5,
                                        onPicturesChanged = { newPictures ->
                                            if (!uiState.isLoading) {
                                                viewModel.updatePhotos(newPictures)
                                            }
                                        },
                                        onImageUpload = { file ->
                                            onPictureUpload(file)
                                        }
                                    )
                                }
                            }
                        }
                    }

                    // 钓点名称
                    item {
                        OutlinedTextField(
                            value = uiState.spotName,
                            onValueChange = { if (!uiState.isLoading) viewModel.updateSpotName(it) },
                            label = {
                                Text(
                                    stringResource(R.string.spot_name),
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            enabled = !uiState.isLoading,
                            colors = TextFieldDefaults.outlinedTextFieldColors(
                                focusedTextColor = MaterialTheme.colorScheme.onSurface,
                                unfocusedTextColor = MaterialTheme.colorScheme.onSurface,
                                cursorColor = MaterialTheme.colorScheme.primary,
                                focusedBorderColor = MaterialTheme.colorScheme.primary,
                                unfocusedBorderColor = MaterialTheme.colorScheme.outline
                            )
                        )
                    }

                    // 位置信息
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                PropertySection(title = stringResource(R.string.location_info)) {
                                    // 显示当前选择的经纬度
                                    if (uiState.latitude != 0.0 && uiState.longitude != 0.0) {
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Column {
                                                Text("纬度: ${uiState.latitude}")
                                                Text("经度: ${uiState.longitude}")
                                            }
                                        }
                                    }

                                    // 操作按钮
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.End,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        // 跳转到地图选择按钮
                                        Button(
                                            onClick = {
                                                if (!uiState.isLoading) {
                                                    val router =
                                                        "${FishingNavigation.MAP_SELECTION}?moduleKey=addSpot"
                                                    navController.navigate(router)
                                                }
                                            },
                                            enabled = !uiState.isLoading,
                                            modifier = Modifier.padding(AppDimensions.SPACING_8)
                                        ) {
                                            Text("在地图上选择")
                                        }

                                        // 使用当前位置按钮
                                        if (uiState.currentLocation != null) {
                                            TextButton(
                                                onClick = {
                                                    if (!uiState.isLoading) {
                                                        viewModel.updateLocation(
                                                            uiState.currentLocation!!.latitude,
                                                            uiState.currentLocation!!.longitude
                                                        )
                                                    }
                                                },
                                                enabled = !uiState.isLoading
                                            ) {
                                                Icon(
                                                    Icons.Default.MyLocation,
                                                    contentDescription = null,
                                                    modifier = Modifier.size(AppDimensions.ICON_SIZE_16)
                                                )
                                                Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
                                                Text("使用当前位置")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 停车方便性
                    item {
                        PropertySection(title = stringResource(R.string.parking_convenience)) {
                            ThreeColumnGrid(
                                listOf(
                                    {
                                        RadioButtonWithLabel(
                                            label = stringResource(R.string.convenient),
                                            selected = uiState.parkingEasy,
                                            onSelect = { viewModel.updateParkingEasy(true) }
                                        )
                                    },
                                    {
                                        RadioButtonWithLabel(
                                            label = stringResource(R.string.inconvenient),
                                            selected = !uiState.parkingEasy,
                                            onSelect = { viewModel.updateParkingEasy(false) }
                                        )
                                    }
                                ))
                        }
                    }

                    // 钓点级别
                    item {
                        PropertySection(title = stringResource(R.string.spot_level)) {
                            val levels = uiState.props.lvls
                            ThreeColumnGrid(levels.map { level ->
                                {
                                    RadioButtonWithLabel(
                                        label = level.name,
                                        selected = uiState.selectedLevel == level.code,
                                        onSelect = { viewModel.updateSelectedLevel(level.code) }
                                    )
                                }
                            })
                        }
                    }

                    // 车到水距离
                    item {
                        PropertySection(title = stringResource(R.string.distance_to_water)) {
                            val distances = uiState.props.distances
                            ThreeColumnGrid(distances.map { distance ->
                                {
                                    RadioButtonWithLabel(
                                        label = distance.name,
                                        selected = uiState.selectedDistance == distance.code,
                                        onSelect = { viewModel.updateSelectedDistance(distance.code) }
                                    )
                                }
                            })
                        }
                    }

                    // 水域类型
                    item {
                        PropertySection(title = stringResource(R.string.water_type)) {
                            val waterTypes = uiState.props.waterTypes
                            ThreeColumnGrid(waterTypes.map { waterType ->
                                {
                                    RadioButtonWithLabel(
                                        label = waterType.name,
                                        selected = uiState.selectedWaterType == waterType.code,
                                        onSelect = { viewModel.updateSelectedWaterType(waterType.code) }
                                    )
                                }
                            })
                        }
                    }

                    // 钓点类型
                    item {
                        PropertySection(title = stringResource(R.string.spot_type)) {
                            val spotTypes = uiState.props.spotTypes
                            ThreeColumnGrid(spotTypes.map { spotType ->
                                {
                                    CheckboxWithLabel(
                                        label = spotType.name,
                                        checked = uiState.selectedSpotType.contains(spotType.code),
                                        onCheckedChange = {
                                            viewModel.toggleSpotType(spotType.code)
                                        }
                                    )
                                }
                            })
                        }
                    }

                    // 鱼类类型
                    item {
                        PropertySection(title = stringResource(R.string.fish_species)) {
                            val fishTypes = uiState.props.fishTypes
                            ThreeColumnGrid(fishTypes.map { fishType ->
                                {
                                    CheckboxWithLabel(
                                        label = fishType.name,
                                        checked = uiState.selectedFishTypes.contains(fishType.code),
                                        onCheckedChange = {
                                            viewModel.toggleFishType(fishType.code)
                                        }
                                    )
                                }
                            })
                        }
                    }

                    // 基本属性
                    item {
                        PropertySection(title = stringResource(R.string.basic_properties)) {
                            ThreeColumnGrid(
                                listOf(
                                    {
                                        CheckboxWithLabel(
                                            label = stringResource(R.string.free_spot),
                                            checked = !uiState.isFree,
                                            onCheckedChange = { viewModel.updateIsFree(it) }
                                        )
                                    },
                                    {
                                        CheckboxWithLabel(
                                            label = stringResource(R.string.forbidden_fishing),
                                            checked = uiState.isForbidden,
                                            onCheckedChange = { viewModel.updateIsForbidden(it) }
                                        )
                                    },
                                    {
                                        CheckboxWithLabel(
                                            label = stringResource(R.string.secret_spot),
                                            checked = !uiState.isPrivate,
                                            onCheckedChange = { viewModel.updateIsPrivate(it) }
                                        )
                                    }
                                ))
                        }
                    }

                    // 描述
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                PropertySection() {
                                    OutlinedTextField(
                                        value = uiState.description,
                                        onValueChange = {
                                            if (!uiState.isLoading) viewModel.updateDescription(it)
                                        },
                                        placeholder = { Text("请输入钓点描述，如鱼情、水深等信息") },
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .height(AppDimensions.CARD_HEIGHT_150),
                                        maxLines = 10,
                                        enabled = !uiState.isLoading
                                    )
                                }
                            }
                        }
                    }

                    // 提交按钮
                    item {
                        Button(
                            onClick = { viewModel.saveSpot() },
                            enabled = uiState.spotName.isNotBlank() && uiState.photos.isNotEmpty() &&
                                    uiState.selectedSpotType.isNotEmpty() && uiState.selectedFishTypes.isNotEmpty() &&
                                    !uiState.isLoading,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(stringResource(R.string.add_spot))
                        }
                    }
                }
            )

            // 加载遮罩
            if (uiState.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background.copy(alpha = 0.7f))
                        .clickable(enabled = false) {},
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(AppDimensions.ICON_SIZE_48)
                    )
                }
            }
        }
    }
}